import { loginForm, logout } from '@/api/login'
import { getUser } from '@/api/system/user'
import { getToken, setToken, removeToken, setRefreshToken, getUserId, setUserId, setUser, setAccount, removeAccount, setLjdm, removeLjdm, removeUserId, setUserRole, removeUserRole } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Message } from 'element-ui'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  userId: getUserId(),
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_REFRESH_TOKEN: (state, refreshToken) => {
    state.refreshToken = refreshToken
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_USERID: (state, id) => {
    state.userId = id
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, code, that, flag } = userInfo
    return new Promise((resolve, reject) => {
      loginForm({ username: username.trim(), password: password, code: code, flag: flag }).then(response => {
        if (response.returnCode !== '00200') {
          Message({
            message: response.msg,
            type: 'error',
            duration: 5 * 1000
          })
          that.errorCount = ++that.errorCount
          return
        }
        const { data } = response
        commit('SET_TOKEN', data.accessToken)
        commit('SET_REFRESH_TOKEN', data.refreshToken)
        commit('SET_USERID', data.userId)
        setToken(data.accessToken)
        setRefreshToken(data.refreshToken)
        setUserId(data.userId)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      getUser({ id: state.userId }).then(async res => {
        localStorage.setItem('UserResourceCode_Key', res.data.resourceCodes)
        commit('SET_ROLES', res.data.roleIds)
        setUser(res.data.realName)
        setAccount(res.data.username)
        setLjdm(res.data.bureauCode)
        setUserRole(res.data.roleIds)
        await dispatch('tagsView/delAllViews', [], { root: true })
        const addRouters = await dispatch('permission/generateRoutes', res.data.routes, { root: true })
        // await dispatch('permission/generateAuth', res.auth, { root: true })
        resetRouter()
        resolve(addRouters)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        // 清除cookie
        removeUserId()
        removeToken()
        removeAccount()
        removeLjdm()
        removeUserRole()
        localStorage.clear()
        // resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
